<template>
  <el-menu
    :default-active="defaultActive"
    :unique-opened="true"
    class="el-menu-vertical-demo"
  >
    <template v-for="item in menu">
      <template v-if="item.child && item.child.length > 0">
        <el-sub-menu
          :key="item.id"
          :index="item.level"
          :disabled="item.meta?.disabled"
          :popper-append-to-body="false"
        >
          <template #title>
            <i :class="[item.meta?.icon]"></i>
            <!-- 添加空格 表示下级-->
            <span> {{ generateSpaces(item.level) }} </span>
            <span slot="title"> {{ item.name }}</span>
          </template>
          <MenuTree
            :menu="item.child"
            :defaultActive="defaultActive"
            @clickItem="clickItemHandle"
          />
        </el-sub-menu>
      </template>
      <template v-else>
        <el-menu-item
          :key="item.id"
          :index="item.level"
          :disabled="item.meta?.disabled"
          :popper-append-to-body="false"
          @click="clickItemHandle(item)"
        >
          <i :class="[item.meta?.icon]"></i>
          <!-- 添加空格 表示下级-->
          <span> {{ generateSpaces(item.level) }} </span>
          <span slot="title">{{ item.name }}</span>
        </el-menu-item>
      </template>
    </template>
  </el-menu>
</template>
 
<script lang="ts">
import { defineComponent, toRefs } from "vue";
import type { PropType } from "vue";
import type { MenuItem } from "@/types/lesson";
export default defineComponent({
  name: "MenuTree",
  props: {
    menu: {
      type: Array as unknown as PropType<any[]>,
      required: true,
      default: () => [],
    },
    defaultActive: {
      type: String as unknown as PropType<string>,
      required: true,
      default: "",
    },
  },
  emits: ["update-active-path", "clickItem"],
  setup(props, context) {
    const { menu, defaultActive } = toRefs(props);

    const generateSpaces = (level: string) => {
      let str = "";
      level
        .split("")
        .filter((it) => it != "-")
        .forEach(() => {
          str += "　";
        });
      return str;
    };

    const clickItemHandle = (item: MenuItem) => {
      context.emit("clickItem", item);
    };

    return {
      clickItemHandle,
      menu,
      defaultActive,
      generateSpaces,
    };
  },
});
</script>
 
<style scoped lang="less">
.el-menu {
  width: 288px;
}
</style>